package com.example.affair.controller;

import com.example.affair.service.UserSevice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
     @Autowired
    private UserSevice userSevice;
//    //JDBC事务管理器
//    @Autowired
//    private DataSourceTransactionManager dataSourceTransactionManager;
    //定义事务
//    @Autowired
//    private TransactionDefinition transactionDefinition;


//    @RequestMapping("/registry")
//    public String registry(String userName,String password){
//        //开启事务
//        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
//        if(userName==null||password==null)return null;
//        userSevice.registryUser(userName,password);
//        //提交事务
//        dataSourceTransactionManager.commit(transactionStatus);
//      //  dataSourceTransactionManager.rollback(transactionStatus);
//        return "用户注册成功";
//    }
    @Transactional(isolation=Isolation.DEFAULT)
    @RequestMapping("/registry")
    public String registry(String userName,String password) throws IOException {
        if(userName==null||password==null)return null;
        userSevice.registryUser(userName,password);
        log.info("用户注册成功");
//        try {
//            int[]arr=new int[2];
//            arr[2]=1;
//        }catch (Exception e){

//            //手动回滚事务
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        if(true){
            throw new IOException();
        }
        return "用户注册成功";
    }
}
